package jdk8.stream;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.junit.Test;

public class StreamDemo {
	@Test
	public void createStream() {
		List<Integer> list = Arrays.asList(12,34,62,654,234,131,198,123);
		// 流是FIFO（先进先出）队列, 遍历所有list元素，添加到流中
		Stream<Integer> stream = list.stream();
		
		Set<String> set = new HashSet<>();
		set.add("abc");
		set.add("abc2");
		set.add("abc3");
		Stream<String> stream2 = set.stream();
		
		Stream<Integer> of = Stream.of(1,2,3,4,5);
		
		// 随机一个int流
		IntStream ints = new Random().ints(10);
	}
	
	@Test
	public void useful() {
		List<Integer> list = Arrays.asList(12,62,12,34,34,62,654,234,131,198,123);
		
		Stream<Integer> s1 = list.stream();
		System.out.println("元素个数:" + s1.count());
		
		Stream<Integer> s2 = list.stream();
		// 只取前三个
		Stream<Integer> limit = s2.limit(3);
		limit.forEach(System.out::println);
		
		Stream<Integer> s3 = list.stream();
		// 重复的只保留一份
		Stream<Integer> distinct = s3.distinct();
		distinct.forEach((t) -> System.out.println(t));
		System.out.println("------------------------");
		
		Stream<Integer> s4 = list.stream();
		// 排序
		Stream<Integer> sorted = s4.sorted();
		sorted.forEach(System.out::println);
		System.out.println("------------------------");
		
		Stream<Integer> filter = list.stream().filter((t)->t>=50);
		filter.forEach(System.out::println);
		System.out.println("------------------------");
		
		Stream<Integer> map = list.stream().map((t)-> t*2);
		map.forEach(System.out::println);
		
		Double collect = list.stream().collect(Collectors.averagingInt(t->t));
		System.out.println(collect);
	}
}
